package esi.t2no1.util;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.namespace.QName;

import org.apache.cxf.binding.soap.SoapFault;
import org.springframework.util.StringUtils;

/**
 * Contains utility methods for web-service operations
 * 
 * @author Kaarel Jõgeva
 */
public class WsUtil {

	/** ID: (\d*) */
	private static final Pattern ID_PATTERN = Pattern.compile("ID: (\\d*)");
	/** ID: \d*([\s\S]*)Payload: */
	private static final Pattern MISC_PATTERN = Pattern.compile("ID: \\d*([\\s\\S]*)Payload: ");
	/** Payload: ([\s\S]*[^--]) */
	private static final Pattern PAYLOAD_PATTERN = Pattern.compile("Payload: ([\\s\\S]*[^--])");

	public static final String ID = "transactionId";
	public static final String MISC = "misc";
	public static final String PAYLOAD = "payload";

	private WsUtil() {
		// Do not allow instances
	}

	public static Map<String, Object> extractLogMessageParts(String message) {
		Map<String, Object> parts = new HashMap<String, Object>(3);

		if (!StringUtils.hasText(message)) {
			return parts;
		}

		// Extract ID
		Integer id = -1;
		Matcher idMatcher = ID_PATTERN.matcher(message);
		if (idMatcher.find()) {
			try {
				id = Integer.parseInt(idMatcher.group(1));
			} catch (NumberFormatException e) {
				// Invalid id? Anyway, lets move on.
			}
		}
		parts.put(ID, id);

		// Extract misc info
		Matcher miscMatcher = MISC_PATTERN.matcher(message);
		String misc = "";
		if (miscMatcher.find()) {
			misc = miscMatcher.group(1).substring(1); // Remove new-line character as well.
		}
		parts.put(MISC, misc);

		// Extract payload
		Matcher payloadMatcher = PAYLOAD_PATTERN.matcher(message);
		String payload = "";
		if (payloadMatcher.find()) {
			payload = payloadMatcher.group(1);
		}
		parts.put(PAYLOAD, payload);

		return parts;
	}

	public static SoapFault createSoapFault(String errorMessage, String errorName) {
		return new SoapFault(errorMessage, new QName("http://service.ws.t2no1.esi/", errorName));
	}

}
